<?php

namespace Admin\Model;

/**
 * Description of AdminModel
 *
 * @author 阿明 symphp@foxmail.com
 */
class AdminModel extends \Think\Model{
    
    /**
     * 管理员-权限-关联模型
     * 管理员-角色-管理模型
     * @var type 
     */
    
    private $_admin_role_model = null;
    private $_admin_permission_model = null;

    /**
     * 实例化需要操作的关联模型
     * @param type $name
     * @param type $tablePrefix
     * @param type $connection
     */
    public function __construct($name = '', $tablePrefix = '', $connection = '') {
        parent::__construct($name, $tablePrefix, $connection);
        $this->_admin_role_model = M('AdminRole');
        $this->_admin_permission_model = M('AdminPermission');
    }

    protected $_validate = array(
        /**
         * 账号不能为空,并且长度为5-16位 不重复
         * 密码不能为空.并且长度为5-16位
         * 验证邮箱
         */
        array('username','require','账号不能为空',self::EXISTS_VALIDATE,'',self::MODEL_INSERT),
        array('username','','该账号已存在',self::EXISTS_VALIDATE,'unique',self::MODEL_INSERT),
        array('password','require','密码不能为空',self::EXISTS_VALIDATE,'',self::MODEL_INSERT),
        array('password','5,16','密码长度为5-16位',self::EXISTS_VALIDATE,'length',self::MODEL_INSERT),
        array('email','email','邮箱格式不正确',self::EXISTS_VALIDATE,'',self::MODEL_INSERT),
        array('username', 'require', '用户名必填', self::MUST_VALIDATE, '', 'login'),
        array('password', 'require', '密码必填', self::MUST_VALIDATE, '', 'login'),
        array('captcha','require','验证码必填',self::MUST_VALIDATE,'','login'),
        array('captcha','check_captcha','验证码错误',self::MUST_VALIDATE,'callback','login'),
    );
    
    protected function check_captcha($code){
        $verify = new \Think\Verify();
        return $verify->check($code);
    }

        /**
     * 自动完成
     * 加入时间 salt 
     */
    
    protected $_auto = array(
        array('salt','\Org\Util\String::randString',self::MODEL_INSERT,'function',6),
        array('add_time', NOW_TIME, self::MODEL_INSERT),
    );
    
    /**
     * 获取列表
     * @param type $filed
     * @return type
     */
    public function getList($filed = '*'){
        return $this->field($filed)->where(array('status'=>1))->select();
        
    }
    
    public function addAdmin(){
        //添加删除id
        unset($this->data['id']);
        //加密密码
        $this->data['password'] = salt_password($this->data['password'], $this->data['salt']);
        //保存基本信息
        if(($admin_id = $this->add())===false){
            return false;
        }
        //保存关联角色
        if($this->_save_role($admin_id)===false){
            $this->error = '保存关联角色失败';
            return false;
        };
        //保存关联权限
        if($this->_save_Permission($admin_id)===false){
            $this->error = '保存关联权限失败';
            return false;
        };
        return true;
       }
       
       /**
        * 保存关联角色
        * @param type $admin_id
        * @return boolean
        */
       private function _save_role($admin_id,$is_new = true){
           //是false就代表要删除,执行更新操作
           if (!$is_new) {
            if($this->_delete_role($admin_id)===false){
                return false;
            }
        }
           //判断是否勾选角色,如果没勾选就不进行保存
           $roles = I('post.role');
           //为空直接返回true
           if(empty($roles)){
               return TRUE;
           }
           //构建数据
           $data = array();
        foreach ($roles as $role) {
            $date[] = array(
                'role_id' => $role,
                'admin_id' => $admin_id,
            );
        }
       return $this->_admin_role_model->addAll($date);
    }
    
    /**
     * 通过id获取admin表
     * @param type $id
     * @return boolean
     */
    public function getAdminInfo($id){
        $row = $this->find($id);
        if($row===false){
            $this->error = '编辑错误';
            return false;
        };
        //获取角色表
        $row['role_ids'] = $this->_admin_role_model->where(array('admin_id'=>$id))->getField('role_id',true);
        //获取关联权限
        $row['permission_ids'] = json_encode($this->_admin_permission_model->where(array('admin_id'=>$id))->getField('permission_id',true));
        //返回
        return $row;
    }

        private function _save_Permission($admin_id,$is_new = true){
           //是false就代表要删除,执行更新操作
           if (!$is_new) {
            if($this->_delete_permission($admin_id)===false){
                return false;
            }
        }
           //判断是否勾选角色,如果没勾选就不进行保存
           $Permissions = I('post.perm');
           //为空直接返回true
           if(empty($Permissions)){
               return TRUE;
           }
           //构建数据
           $date = array();
            foreach ($Permissions as $Permission) {
                $date[] = array(
                    'permission_id' => $Permission,
                    'admin_id' => $admin_id,
                );
            }
       return $this->_admin_permission_model->addAll($date);
    }
    
    public function updateAdmin(){
        //保存传递的数据
        $request_data = $this->data;
        //保存角色关联
        if ($this->_save_role($request_data['id'], false) === false) {
            $this->error = '更新角色关联失败';
            return false;
        }
        //保存权限关联
        if($this->_save_Permission($request_data['id'], false) === false){
             $this->error = '更新权限关联失败';
            return false;
        }
        return true;
    }
    
    /**
     * 删除基本信息和关联表
     */
    public function delectAdmin($id){
        if($this->delete($id) === false){
            return false;
        }
        if($this->_delete_role($id) === false){
            $this->error = '删除角色表失败';
            return false;
        }
        if($this->_delete_permission($id) === false){
            $this->error = '删除权限表失败';
            return false;
        }
        return true;
    }

        /**
     * 删除数据
     * @param type $admin_id
     * @return booleans
     */
    private function _delete_role($admin_id) {
        if ($this->_admin_role_model->where(array('admin_id' => $admin_id))->delete() === false) {
            return false;
        }
    }
    
    private function _delete_permission($admin_id) {
        if ($this->_admin_permission_model->where(array('admin_id' => $admin_id))->delete() === false) {
            return false;
        }
    }
    
  
    public function login(){
        $request_data = $this->data;
        //1.验证用户名是否存在
        $userinfo = $this->getByUsername($this->data['username']);
        if(empty($userinfo)){
            $this->error = '用户不存在';
            return false;
        }
        //2.自动验验证码(验证码必填)  可以用自动验证的自定义函数,调用函数的时候传值  再用验证码类的check方法返回结果
        //3.密码验证,调用function里的salt_password方法返回输入密码和salf的加密结果进行匹配
        $password = salt_password($request_data['password'], $userinfo['salt']);
        if($password != $userinfo['password']){
            $this->error = '密码错误';
            return false;
        }
        //成功返回true
        return true;
    }

}
